package com.nononsenseapps.feeder.model

import android.app.Application
import androidx.appcompat.app.AppCompatActivity
import androidx.collection.ArrayMap
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.nononsenseapps.feeder.ui.base.CoroutineScopedViewModel
import com.nononsenseapps.feeder.db.entity.Feed
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import com.nononsenseapps.feeder.db.room.ID_UNSET
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map


class FeedListViewModel(application: Application): CoroutineScopedViewModel(application) {

    val liveFeedsWithUnreadCounts = feedDao.loadLiveFeedsWithUnreadCounts().map{feeds->
        val topTag = FeedUnreadCount(id = ID_ALL_FEEDS)
        val tags: MutableMap<String, FeedUnreadCount> = ArrayMap()
        val data: MutableList<FeedUnreadCount> = mutableListOf(topTag)
        feeds.forEach { feed ->
            if (feed.tag.isNotEmpty()) {
                if (!tags.contains(feed.tag)) {
                    val tag = FeedUnreadCount(tag = feed.tag)
                    data.add(tag)
                    tags[feed.tag] = tag
                }

                tags[feed.tag]?.let { tag ->
                    tag.unreadCount += feed.unreadCount
                }
            }
            topTag.unreadCount += feed.unreadCount
            data.add(feed)
        }
        data.sortWith(Comparator { a, b -> a.compareTo(b) })
        data
    }

    @JvmName("getLiveFeedsWithUnreadCounts1")
    fun getLiveFeedsWithUnreadCounts(): Flow<List<FeedUnreadCount>> {
        return liveFeedsWithUnreadCounts.map{ feedUnreadCounts ->
            var ret = feedUnreadCounts.filter {  feedUnreadCount ->  feedUnreadCount.unreadCount > 0 && feedUnreadCount.id > ID_UNSET }.sortedWith(compareBy({ it.attentionLevel }, { it.unreadCount })).reversed()
            if (ret.size > 20)
                ret = ret.slice(0..19)
            ret
        }
    }

    fun getLiveFeeds():List<Feed> {
          return feedDao.loadSubscribeFeeds()
    }

    fun getLiveHotFeeds(hotIdList:List<Long>):List<Feed>{
        return getLiveFeeds().filter {hotIdList.contains(it.id)}
    }
}

/*fun AppCompatActivity.getFeedListViewModel(): FeedListViewModel {
    return ViewModelProvider(this).get(FeedListViewModel::class.java)
}

fun Fragment.getFeedListViewModel(): FeedListViewModel {
    return ViewModelProvider(activity!!).get(FeedListViewModel::class.java)
}*/
